angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {

  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  // Form data for the login modal
  $scope.loginData = {};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.modal.hide();
  };

  // Open the login modal
  $scope.login = function() {
    $scope.modal.show();
  };

  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
    console.log('Doing login', $scope.loginData);

    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
    $timeout(function() {
      $scope.closeLogin();
    }, 1000);
  };
})

.controller('LoginCtrl', function($scope,$state) {
    $scope.signIn = function(){
      $state.go("home",{});
    }
})

  .controller('HomeCtrl', function($scope,$state) {

    var weekday=new Array(7);
    weekday[0]="日";
    weekday[1]="一";
    weekday[2]="二";
    weekday[3]="三";
    weekday[4]="四";
    weekday[5]="五";
    weekday[6]="六";
    var d = new Date();
    $scope.year = d.getFullYear();
    $scope.month = d.getMonth()+1;
    $scope.date = d.getDate();
    $scope.day = weekday[d.getDay()];
    $scope.apm = "AM";
    $scope.time = d.toLocaleTimeString();
    $scope.time = $scope.time.substring(0,$scope.time.lastIndexOf(":"));
    if($scope.time.indexOf("下午")==0){
      $scope.apm = "PM";
      $scope.time = $scope.time.replace("下午","");
    }
    else if($scope.time.indexOf("上午")==0){
      $scope.apm = "AM";
      $scope.time = $scope.time.replace("上午","");
    }
    $scope.sign =  function(){
      $state.go("sign",{});
    };

    $scope.report =  function(){
      $state.go("report",{});
    };
  })
  .controller('ReportCtrl', function($scope) {
    $scope.data = {
      apm: 'ng'
    };
    var radioValue = "";//时间段

    var weekday=new Array(7);
    weekday[0]="日";
    weekday[1]="一";
    weekday[2]="二";
    weekday[3]="三";
    weekday[4]="四";
    weekday[5]="五";
    weekday[6]="六";
    var d = new Date();
    $scope.year = d.getFullYear();
    $scope.month = d.getMonth()+1;
    $scope.date = d.getDate();
    $scope.day = weekday[d.getDay()];
    $scope.apm = "AM";
    $scope.time = d.toLocaleTimeString();
    $scope.time = $scope.time.substring(0,$scope.time.lastIndexOf(":"));
    if($scope.time.indexOf("下午")==0){
      $scope.apm = "PM";
      $scope.time = $scope.time.replace("下午","");
    }
    else if($scope.time.indexOf("上午")==0){
      $scope.apm = "AM";
      $scope.time = $scope.time.replace("上午","");
    }
    $scope.radio_list = [
      { text: "上午", value: "am" },
      { text: "下午", value: "pm" },
      { text: "全天", value: "apm" },
    ];

    $scope.radioChange = function(item) {
      radioValue = item.value
      console.log("Selected apm, text:", item.text, "value:", item.value);
    };


  })
//http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-placeapi
.controller('SignCtrl', function($scope,$http,$ionicActionSheet,$cordovaDatePicker,$cordovaGeolocation) {
    //$scope.date = new Date().getTime();
    $scope.change_year = "";
    $scope.change_month = "";
    var weekday=new Array(7);
    weekday[0]="日";
    weekday[1]="一";
    weekday[2]="二";
    weekday[3]="三";
    weekday[4]="四";
    weekday[5]="五";
    weekday[6]="六";
    var d = new Date();
    $scope.change_year = $scope.year = d.getFullYear();
    $scope.change_month = $scope.month = d.getMonth()+1;
    $scope.date = d.getDate();
    $scope.day = weekday[d.getDay()];
    $scope.apm = "AM";
    $scope.time = d.toLocaleTimeString();
    $scope.time = $scope.time.substring(0,$scope.time.lastIndexOf(":"));
    if($scope.time.indexOf("下午")==0){
      $scope.apm = "PM";
      $scope.time = $scope.time.replace("下午","");
    }
    else if($scope.time.indexOf("上午")==0){
      $scope.apm = "AM";
      $scope.time = $scope.time.replace("上午","");
    }
    $scope.sign_list = [];//储存签到数据
    var companys = [];
    var companys_text = [];
    function successCallback(data) {
      data.replace("\n","");
      data.replace(" ","");
      var lat = data.substring(data.indexOf("latitude")+10,data.indexOf("lontitude"));
      var lon = data.substring(data.indexOf("lontitude")+11,data.indexOf("radius"));
      getdata(lat+","+lon);
    };
    function failedCallback(error) {
      alert("error"+error);
    }
    //if (window.cordova && window.cordova.plugins.Keyboard) {
      // 进行定位

    //}

    //var onSuccess = function(position) {
    //  alert('Latitude: '          + position.coords.latitude          + '\n' +
    //  'Longitude: '         + position.coords.longitude         + '\n' +
    //  'Altitude: '          + position.coords.altitude          + '\n' +
    //  'Accuracy: '          + position.coords.accuracy          + '\n' +
    //  'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
    //  'Heading: '           + position.coords.heading           + '\n' +
    //  'Speed: '             + position.coords.speed             + '\n' +
    //  'Timestamp: '         + position.timestamp                + '\n');
    //};
    //function onError(error) {
    //  alert('code: '    + error.code    + '\n' +
    //  'message: ' + error.message + '\n');
    //}
    //navigator.geolocation.getCurrentPosition(onSuccess, onError);


    //var posOptions = {maximumAge: 30000, timeout: 5000, enableHighAccuracy: false};
    //$cordovaGeolocation
    //  .getCurrentPosition(posOptions)
    //  .then(function (position) {
    //    alert("position"+position);
    //    var lat  = position.coords.latitude
    //    var long = position.coords.longitude
    //    getdata(lat+","+long);
    //  }, function(err) {
    //    alert('code: '    + err.code    + '\n' +
    //    'message: ' + err.message + '\n');
    //  });
    var options = {
      date: new Date(),
      mode: 'date', // or 'time'
      allowOldDates: true,
      allowFutureDates: true,
      doneButtonLabel: 'DONE',
      doneButtonColor: '#F2F3F4',
      cancelButtonLabel: 'CANCEL',
      cancelButtonColor: '#000000'
    };
    $scope.changeMonth = function(){
      $cordovaDatePicker.show(options).then(function(date){
        alert(date);
        $scope.change_year = date.getFullYear();
        $scope.change_month = date.getMonth()+1;
      });
    }
    $scope.signIn = function(){
      baidu_location.getCurrentPosition(successCallback, failedCallback);
    }
    //lat<纬度>,lng<经度>  'location': "40.072692,116.240894",
    function getdata(location){
      alert(location);
      $http({
        method: 'POST',
        url: 'http://api.map.baidu.com/place/v2/search',
        params: {
          'query': "公司",
          'location': location,
          'radius': 2000,
          'output': "json",
          'ak': "4fnwY1lCfnnoW3a55aKaMf9g"
        }
      }).success(function(data) {
        companys = data.results;
        companys_text = [];
        for (var i in companys) {
          companys_text.push({
            text: companys[i].name
          });
        }
        $ionicActionSheet.show({
          buttons: companys_text ,
          cancelText: '关闭',
          cancel: function() {
            return true;
          },
          buttonClicked: function(index) {
            switch (index) {
              case 0:
              case 1:
              case 2:
              case 3:
              case 4:
              case 5:
              case 6:
              case 7:
              case 8:
              case 9:
                $scope.sign_list.push({
                  time: new Date().getTime(),
                  position: companys[index].name
                })
                break;
              default:
                break;
            }
            return true;
          }
        });

      }).error(function(data) {
        alert(data);
      });
    }
})
